﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using System;

namespace BF
{

    /// <summary>
    /// 将Language文件根据语言拆分
    /// </summary>
    public static class LanguageSplit
    {

        private static string orginFile = Application.dataPath + "/__BF/Editor/Language/Language.csv";
        private static string outDir = Application.dataPath + "/__BF/Resources/Language/";

        /// <summary>
        /// 分割符
        /// </summary>
        private const char STX = (char)0x02;
        /// <summary>
        /// 换行
        /// </summary>
        private const string SEP = "\r\n";


        [MenuItem("BF/拆分多语言文件")]
        public static void SplitWithoutEncodingConvert()
        {
            try
            {
                EncodingUtils.ConvertFileToUTF8(orginFile);
            }
            catch (Exception e)
            {
                Debug.LogError("------------------------------");
                Debug.LogError($"Convert file to UTF-8 error, {orginFile}");
                Debug.LogException(e);
                Debug.LogError("------------------------------");
            }

            Split(orginFile, outDir);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }


        private static void Split(string orginDir, string outDir)
        {
            string fileInfo = File.ReadAllText(orginDir);
            List<List<string>> csvInfo = CsvUtil.LoadCsv(fileInfo);

            int rowCount = csvInfo[0].Count;

            for (int row = 1; row < rowCount; ++row)
            {
                Split(csvInfo, row, outDir);
            }
        }

        private static void Split(List<List<string>> csvInfo, int row, string savePath)
        {
            string name = csvInfo[1][row];
            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            StringBuilder sb = new StringBuilder();
            for (int line = 2; line < csvInfo.Count; ++line)
            {
                try
                {
                    string key = csvInfo[line][0];
                    string value = csvInfo[line][row];

                    sb.Append(key);
                    sb.Append(STX);
                    sb.Append(value);
                    sb.Append(SEP);
                }
                catch(Exception e)
                {
                    Debug.LogError($"Split language file error --> line:{line}, row:{row}");
                    throw e;
                }
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            string saveFile = Path.Combine(savePath, $"{name}.bytes");
            File.WriteAllBytes(saveFile, Encoding.UTF8.GetBytes(sb.ToString()));

            Debug.Log($"[拆分多语言文件][{name}] Success, {saveFile}");
        }
    }
}
#endif